<?php
/**
 * Created by PhpStorm.
 * User: lixy
 * Date: 2016/4/25
 * Time: 13:17
 */

namespace app\controllers;

use app\lib\Tools;
use app\lib\WXBaseController;
use app\lib\wxpay\WxPayApi;
use app\lib\wxpay\WxPayTools;
use app\lib\wxpay\WxPayUnifiedOrder;
use app\models\BizDao;
use app\models\FxDao;
use app\models\HomeDao;
use app\models\T_WX_PAY_LOG;
use app\models\weixin\T_WXMALL_USER;
use app\models\WxGoodDao;
use Yii;
use app\lib\WebService;

use yii\web\User;

class WxGoodController extends WXBaseController
{

    public function actionGoodsList()
    {
        static::__validUser();
        $userid = static::getSessionUserid();
        $TOTALNUM = WxGoodDao::calc_cart_order_TOTALNUM($userid);
        return $this->render("goods-list", ['TOTALNUM' => $TOTALNUM]);
    }

//shopping-cart
    public function actionShoppingCart()
    {


        return $this->render("shopping-cart", []);
    }

    /**
     * 创建单个产品订单
     * create-goods-to-order-handle
     */
    public function actionCreateGoodsToOrderHandle($goods_code, $address_id = '')
    {
        $msg = "";
        $flag = 0;
        //$userid
        static::__validUser();
        $userid = static::getSessionUserid();
        $user_info = T_WXMALL_USER::getUserByUserid($userid);
        $user_info = $user_info[0];
        $re = FxDao::get_CurrentIndex($userid);
        $discount = $re[0]['DISCOUNT'];

        //取得商品列表 图片 名称 积分
        $order_goods_List = WxGoodDao::get_GoodsInfoAndImgByCode($goods_code);
        $TOTALPRICE = 0;
        if ($order_goods_List != null && $order_goods_List != '') {
            $order_goods_List[0]['COUNT'] = 1;
            $TOTALPRICE = $order_goods_List[0]['PRICE'];
        }

        //取得用户积分
        $integral = 0;// User::getUserIntegral($userid);
        //取得用户收货地址
//        $receiver = WxGoodDao::getReceiverAddress($userid);
        //获取地址
        $address = HomeDao::getUserAddress($address_id, static::getSessionUserid());
        //计算需支付的积分 和 需支付的现金
        $payIntegral = 0;
        $payCash = 0;
        if ($integral >= $TOTALPRICE) {
            $payIntegral = $TOTALPRICE;
            $payCash = 0;
        } else {
            $payIntegral = $integral;
            $payCash = ($TOTALPRICE - $integral);
        }

        //返回  order_goods_List（产品列表） TOTALPRICE（合计金额） integral（用户积分账户） payIntegral（需支付的积分） payRMB（需支付的现金）
        return $this->render("order-form", ['order_type' => 2, 'order_goods_List' => $order_goods_List
            , 'TOTALPRICE' => $TOTALPRICE, 'integral' => $integral, 'pay_integral' => $payIntegral, 'pay_rmb' => $payCash, 'address' => $address,
            'user_info' => $user_info,
            'discount' => $discount,]);
    }

    /**
     * 创建购物车订单
     * create-cart-to-order-handle
     */
    public function actionCreateCartToOrderHandle($address_id = '')
    {
        static::__validUser();
        $msg = "";
        $flag = 0;
        //$userid

        $userid = static::getSessionUserid();
        $user_info = T_WXMALL_USER::getUserByUserid($userid);
        $user_info = $user_info[0];
        $re = FxDao::get_CurrentIndex($userid);
        $discount = $re[0]['DISCOUNT'];


        //取得购买的商品列表 图片 名称 积分 数量
        $order_goods_List = WxGoodDao::getCartPayGoodsDetail($userid);
        //取得订单合计积分金额
        $TOTALPRICE = WxGoodDao::getCartPayTotalprice($userid);
        //取得用户积分
        $integral = 0;//User::getUserIntegral($userid);

        //获取地址
        $address = HomeDao::getUserAddress($address_id, static::getSessionUserid());

        //返回  order_goods_List（产品列表） TOTALPRICE（合计金额） integral（用户积分账户） payIntegral（需支付的积分） payRMB（需支付的现金）
        return $this->render("order-form", ['order_type' => 1, 'order_goods_List' => $order_goods_List
            , 'TOTALPRICE' => $TOTALPRICE, 'address' => $address,
            'user_info' => $user_info,
            'discount' => $discount,]);

    }


    /**
     * 加入购物车 add-goods-to-cart-handle
     */
    public function actionAddGoodsToCartHandle()
    {
        $msg = "";
        $flag = 0;

        //$userid,$goods_code
        $userid = static::getSessionUserid();
        $goods_code = static::getRequestPost("goods_code");
        $stock = WebService::nc_getGiftStock($goods_code);
        if ($stock <= 0) {
            return $this->renderJson(null, 1, '库存不足');
        }
        $re = WxGoodDao::add_art($userid, $goods_code);

        if ($re == 0) {
            $cart_totalnum = WxGoodDao::calc_cart_order_TOTALNUM($userid);
            $goods_num = WxGoodDao::calc_cart_goods_TOTALNUM($userid, $goods_code);
        } else {
            $flag = 1;
            $msg = $re;
            $cart_totalnum = null;
        }
        return $this->renderJson(['TOTALNUM' => $cart_totalnum, 'GOODSNUM' => $goods_num], $flag, $msg);
    }

    /**
     * 获取购物车信息 get-goods-cart-handle
     */
    public function actionGetGoodsCartHandle()
    {
        $userid = static::getSessionUserid();

        $cartList = WxGoodDao::get_shopping_cartList($userid);
        if ($cartList != null && count($cartList) > 0) {
            foreach ($cartList as &$goods) {
                $goods['STOCK'] = WebService::nc_getGiftStock($goods['GOODS_CODE']);
            }
        }
        $TOTALPRICE = 0;//intval(Cart::calc_cart_order_TOTALPRICE($userid));
        $TOTALNUM = intval(WxGoodDao::calc_cart_order_TOTALNUM($userid));

        return $this->renderJson(['cartList' => $cartList, 'TOTALPRICE' => $TOTALPRICE, 'TOTALNUM' => $TOTALNUM]);
    }

    /**
     * 增减购物车某产品数量 inc-goods-to-cart-handle
     */
    public function actionIncGoodsToCartHandle()
    {

        //$userid,$goods_code
        $userid = static::getSessionUserid();
        $goods_code = static::getRequestPost("goods_code");
        $addnum = static::getRequestPost("addnum");
        $updateCount = WxGoodDao::inc_cart_num($userid, $goods_code, $addnum);
        if ($updateCount == 0) {
            $msg = "增减数量失败";
            $status = 1;
        } else {
            $msg = '';
            $status = 0;
        }

        return $this->renderJson(null, $status, $msg);
    }

    /**
     * 删除购物车某产品 del-goods-to-cart-handle
     */
    public function actionDelGoodsToCartHandle()
    {

        //$userid,$goods_code
        $userid = static::getSessionUserid();
        $goods_code = static::getRequestPost("goods_code");

        $updateCount = WxGoodDao::delete_cart_goods($userid, $goods_code);
        if ($updateCount == 0) {
            $msg = "删除失败";
            $status = 1;
        } else {
            $status = 0;
            $msg = '';
        }
        return $this->renderJson(null, $status, $msg);
    }

    /**
     * 清空购物车 clear-cart-handle
     */
    public function actionClearCartHandle()
    {
        //$userid
        $userid = static::getSessionUserid();

        $updateCount = WxGoodDao::delete_cart($userid);
        if ($updateCount == 0) {
            $msg = "删除失败";
            $status = 1;
        } else {
            $status = 0;
            $msg = '';
        }
        return $this->renderJson(null, $status, $msg);
    }


    /**
     * 创建虚拟商品订单
     * create-virtual-goods-to-order-handle
     */
    public function actionCreateVirtualGoodsToOrderHandle($goods_code)
    {
        static::__validUser();
        $msg = "";
        $flag = 0;
        //$userid

        $userid = static::getSessionUserid();
        $user_info = T_WXMALL_USER::getUserByUserid($userid);
        $user_info = $user_info[0];

        $goods_Info = WxGoodDao::get_Goods($goods_code);
        if ($goods_Info != null && $goods_Info['goods'] != null) {
            $goods_Info['goods']['STOCK'] = WebService::nc_getGiftStock($goods_Info['goods']['GOODS_CODE']);
        }
        $TOTALPRICE = $goods_Info['goods']['PRICE'];
//        var_dump($goods_Info['goods']['GOODS_NAME']);
//        exit();

        return $this->render("order-virtual-form", ['user_info' => $user_info, 'goods_Info' => $goods_Info, 'TOTALPRICE' => $TOTALPRICE]);
    }


    /**
     * get-goods-list-handle
     * 查询产品列表信息
     */
    public function actionGetGoodsListHandle()
    {
        static::__validUser();
        $openid = static::getSessionOpenid();

        $request = Yii::$app->request;
        $start = $request->post("start");
        $pagesize = $request->post("pagesize");
        $category = $request->post("category");
        $filter = $request->post("filter");
        $order = $request->post("order");
        $goodsList = WxGoodDao::get_GoodsList($start, $pagesize, $category, $order, $filter, $openid);

        return $this->renderJson(['goodsList' => $goodsList]);
    }

    /**
     * 跳转到产品筛选
     * @param int $category
     * @return string
     */
    public function actionGoodsQuery($category = '0')
    {
        return $this->render("goods-query", ['category' => $category]);
    }

    /**
     * goods-detail
     * 查询产品详情
     * @param $goods_code
     * @return string
     */
    public function actionGoodsDetail($goods_code)
    {
        static::__validUser();
        $userid = static::getSessionUserid();

        $result = WxGoodDao::get_Goods($goods_code);
        $record = $result['goods'];
        /* $goods_code = $re['GOODS_CODE'];
         $goods_name = $re['GOODS_NAME'];
         $goods_price = $re['PRICE'];
         $goods_spec=$re['GOODS_SPEC'];
         $goods_type=$re['GOODS_TYPE'];
         $goods_pinpai=$re['GOODS_PINPAI'];
         $detail_html = $re['GOODS_DETAIL_HTML'];
         $img_list = $re['GOODS_DETAILIMG_URL'];*/
        $re_goods_img_list = $result['imgList'];
        if ($record == false) {
            echo "没有这个产品";
            exit;
        }
        //$re_goods_img_list = WxGoodDao::get_GoodsImageImageByCode($goods_code);
        $cart_totalnum = WxGoodDao::calc_cart_order_TOTALNUM($userid);
        $goods_num = WxGoodDao::calc_cart_goods_TOTALNUM($userid, $goods_code);
        $stock = WebService::nc_getGiftStock($goods_code);

        return $this->render("goods-detail", ['goods_code' => $goods_code, 'record' => $record, 'TOTALNUM' => $cart_totalnum, 'GOODSNUM' => $goods_num, 'goods_img' => isset($re_goods_img_list) ? $re_goods_img_list : $record['GOODS_DETAILIMG_URL'], 'stock' => $stock]);
    }

    /**
     * 跳转到产品分类选择
     * @return string
     */
    public function actionGoodsCategory()
    {
        static::__validUser();
        $openid = static::getSessionOpenid();
        $categoryList = WxGoodDao::get_Category($openid);
        return $this->render("goods-category", ['categoryList' => $categoryList]);
    }


    /**
     * 更改购物车产品选中状态
     */
    public function actionUpdateCartGoodsSelected()
    {
        //$userid
        $userid = static::getSessionUserid();
        $goodslist = static::getRequestPost("goodslist");
        if ($goodslist == null || $goodslist == '') {
            $msg = "请选择需要结算的产品";
            $status = 1;
        } else {
            //修改购物车产品选中状态
            //首先取消所有产品选中状态(规避用户从订单确认中返回后再从新选择另一批产品进行结算，所以得先去掉之前选择状态)
            WxGoodDao::update_cart_unselected($userid);
            foreach ($goodslist as $goods) {
                WxGoodDao::update_cart_selected($userid, $goods);
            }
            $status = 0;
            $msg = '';
        }
        return $this->renderJson(null, $status, $msg);
    }

    /**
     * add-rece-address
     * @param $orderId
     */
    public function actionAddReceAddress($order_type, $goods_code)
    {
        //$userid
        $userid = static::getSessionUserid();
        //取得用户收货地址
        $receiver = WxGoodDao::getReceiverAddress($userid);
        return $this->render("rece-address-add", ['order_type' => $order_type, 'goods_code' => $goods_code, 'receiver' => isset($receiver) ? $receiver : null]);

    }

    /**
     * save-user-address-handle
     */
    public function actionSaveUserAddressHandle()
    {
        $msg = "";

        //$userid,
        $userid = static::getSessionUserid();
        $rece_name = static::getRequestPost("rece_name");
        $rece_phone = static::getRequestPost("rece_phone");
        $rece_address = static::getRequestPost("rece_address");
        $sheng = static::getRequestPost("sheng");
        $shi = static::getRequestPost("shi");
        $qu = static::getRequestPost("qu");

        //保存用户收货地址信息
        $rtstatus = WxGoodDao::saveReceiverAddress($userid, $rece_name, $rece_phone, $rece_address, $sheng, $shi, $qu);

        if ($rtstatus == 0) {
            $status = 0;
        } else {
            $msg = "地址保存失败";
            $status = 1;
        }
        return $this->renderJson(null, $status, $msg);
    }

    /**
     * get-area-handle
     * 获得地区三级体系
     */
    public function actionGetAreaHandle()
    {
        $parent_id = static::getRequestPost("parent_id");

        if ($parent_id == null) {
            $others = WxGoodDao::getAreaList_sheng();
        } else {
            $others = WxGoodDao::getAreaList_other($parent_id);
        }

        return $this->renderJson(['others' => $others]);
    }


    /**
     * 判断地址是否存在
     * @param string $address_id
     * @return string
     */
    public function actionIsExistAddress($address_id = '')
    {
        $address = HomeDao::getUserAddress($address_id, static::getSessionUserid());
        return $this->renderJson(['address' => $address]);
    }

    /**
     * order-form-handle
     * 订单支付确认
     */
    public function actionOrderFormHandle()
    {
        //$userid
        $userid = static::getSessionUserid();
        $order_type = static::getRequestPost("order_type");
        $order_goods_code = static::getRequestPost("goods_code");
        $coin = static::getRequestPost("coin");
        $count = static::getRequestPost("count");
        if ($count == null) {
            $count = 1;
        }
        $phone = static::getRequestPost("phone"); //虚拟商品接收手机号
        if ($phone == null) {
            $phone = '';
        }

        //order_type = 1 代表从购物车下的订单  =2 代表单个产品快捷下单
        $orderId = null;
        if ($order_type == 1) {
            $orderId = WxGoodDao::createNewOrder($userid, $coin);
        } else if ($order_type == 2) {
            $orderId = WxGoodDao::createNewOrderByGoods($userid, $order_goods_code, $coin, $count, $phone);
        }

        if ($orderId != null) {
            $status = 0;
            $msg = '';
        } else {
            $msg = "订单确认失败" + $orderId;
            $status = 1;
        }
        return $this->renderJson(['order_id' => $orderId], $status, $msg);
    }

    // 订单详情
//    public  function actionOrderDetail($order_id)
//    {
//        $userid =static::getSessionUserid();
//        $user_info= T_WXMALL_USER::getUserByUserid($userid);
//        $user_info=$user_info[0];
//        $re=FxDao::get_CurrentIndex($userid);
//        $discount=$re[0]['DISCOUNT'];
//
//
//        if (!isset($order_id)) {
//            static::dump_info('Invalid "order id" params.');
//
//        }
//        $order = WxGoodDao::getOrderById($order_id);
//
//        $currentUserId =static::getSessionUserid();
//        if ($order['USER_ID'] != $currentUserId) {
//            static::dump_info('this order is not your data.');
//        }
//
//        $goodsList = WxGoodDao::getOrderGoodsDetail($order_id);
//
//        $orderTotalIntegral =0;// Order::getOrderTotalIntegral($order_id);
//
//        $userIntegral =$user_info['DORACOIN_ACCOUNT'];// User::getUserIntegral($currentUserId);
//
//
//        return $this->render('order-detail',
//            [
//                'order' => $order,
//                'goodsList' => $goodsList,
//                'orderTotalIntegral' => $orderTotalIntegral,
//                'userIntegral' => $userIntegral,
//            ]);
//    }

    // 取消订单 cancel-order-handle
//    public  function actionCancelOrderHandle()
//    {
//        $orderId = Yii::$app->request->post('order_id');
//        $order = WxGoodDao::getOrderById($orderId);
//
//        if (!isset($order)) {
//            return $this->renderJson(null, 1, '未找到此订单');
//        }
//
//        $currentUserId = static::getSessionUserid();
//        if ($order['USER_ID'] != $currentUserId) {
//            return $this->renderJson(null, 1, '当前用户信息不符。');
//        }
//
//        WxGoodDao::setOrderStatusByCode($order['CODE'], 20);
//        return $this->renderJson(null, 0);
//    }


//订单列表Frings
    public function actionOrderList()
    {
        return $this->render("order-list");
    }

//订单列表分页类容Frings
    public function actionOrderListOrderPartView()
    {
        $request = \Yii::$app->request;
        $page = $request->post("page");
        $pageSize = $request->post("pageSize");


        static::__validUser();

        $userId = static::getSessionUserid();

        $orderList = WxGoodDao::getOrderList($userId, $page, $pageSize);
        foreach ($orderList as &$order) {
            $goodsList = WxGoodDao::getOrderGoodsDetail($order['ID']);

            $order["goods_count"] = 0;
            $order["goods_sum_price"] = 0;

            if (count($goodsList) > 0) {
                foreach ($goodsList as $goods) {
                    $order["goods_count"] += $goods["COUNT"];
                    $order["goods_sum_price"] += $goods["PRICE"] * $goods["COUNT"];
                }
            }
            $order['goodsList'] = $goodsList;
            $order["status_text"] = WxGoodDao::getOrderStatusText($order["STATUS"]);
        }

        return $this->render('order-list-order-part-view', ['orderList' => $orderList]);
    }

    //订单详情Frings 合并到统一的支付路径下
    public function actionOrderDetail($order_id)
    {
        return $this->redirect(["wx-pay/order-detail", 'order_id' => $order_id]);
    }

    //取消订单
    public function actionCancelOrderHandle()
    {
        $orderId = \Yii::$app->request->post('order_id');
        $order = WxGoodDao::getOrderById($orderId);

        if (!isset($order)) {
            return $this->renderJson(null, 1, '未找到此订单');
        }

        static::__validUser();
        $currentUserId = static::getSessionUserid();
        if ($order['USER_ID'] != $currentUserId) {
            return $this->renderJson(null, 1, '当前用户信息不符。');
        }

        if ($order['STATUS'] != '21') {
            WxGoodDao::setOrderStatusByCode($order['ID'], 20);
            return $this->renderJson(null, 0);
        }
        return $this->renderJson(null, 1, '不能取消当前订单。');
    }
//wx-pay-order-handle
// 微信支付下单
    public function actionWxPayOrderHandle()
    {
       try {
           $orderId = Yii::$app->request->post('order_id');
           $order = WxGoodDao::getOrderById($orderId);

           if (!isset($order)) {
               return $this->renderJson(null, 10, '未找到此订单。');
           }

           $currentUserId = static::getSessionUserid();
           if ($order['USER_ID'] != $currentUserId) {
               return $this->renderJson(null, 1, '当前用户信息不符。');
           }
           $user_info = T_WXMALL_USER::getUserByUserid($currentUserId);
           $user_info = $user_info[0];
           $userDoraCoin = $user_info['DORACOIN_ACCOUNT'];


           if ($userDoraCoin < $order['COIN']) {
               return $this->renderJson(null, -1, '当前用户朵拉币不足！');
           }

           if ($order['STATUS'] == 1) {
               //判断库存，库存不足不能进行支付
               $goodsList = WxGoodDao::getOrderGoodsDetail($orderId);
               if ($goodsList != null && count($goodsList) > 0) {
                   $msg = '';
                   foreach ($goodsList as $goods) {
                       $goods['STOCK'] = WebService::nc_getGiftStock($goods['GOODS_CODE']);
                       if ($goods['COUNT'] > $goods['STOCK']) {
                           $msg = $msg . $goods['GOODS_NAME'] . '当前库存为：' . $goods['STOCK'] . ',你的购买量已经超过了库存；';
                       }
                   }

                   if ($msg != '') {
                       return $this->renderJson(null, 120, $msg);
                   }
               }

               $order_code = $order['CODE'];
               $current_coin = $order['COIN'];
               //计算价格
               $result = BizDao::P_WXMALL_CALC_PRICE($currentUserId, $current_coin, $order_code);

               if ($result['RESULTS'] != 1) {
                   return $this->renderJson(null, -1, '计算价格订单失败！' . $result['RESULTS']);
               }
               $price = $result['realPrice'];
               $price = floatval($price) * 100;
               //附加数据
               $attach = '';
               if ($current_coin != '0') {
                   $attach = "current_coin:{$current_coin};";
               }
               //加入订单号
               $attach = $attach . "order_no:{$order_code};";
               $random_order = Tools::build_order_no('sp_');


               $openId = static::getSessionOpenid();
               $nickname = static::getSessionValue(static::sessionKey)->nickname;
               //测试用
               if (YII_ENV == 'dev' && $price > 0) {
                   return $this->renderJson(['testcode' => $order_code, 'coin' => $current_coin, 'price' => $price], 1111);
               }
               if ($price > 0) {
                   $input = new WxPayUnifiedOrder();
                   $input->SetBody($nickname . '的订单');
                   $input->SetOut_trade_no($random_order);
                   $input->SetTotal_fee($price);
                   $input->SetTime_start(date("YmdHis"));
                   $input->SetTime_expire(date("YmdHis", time() + 600));
                   $input->SetNotify_url(PAYURL);
                   $input->SetTrade_type("JSAPI");
                   $input->SetOpenid($openId);
                   $input->SetAttach($attach);
                   $wxOrder = WxPayApi::unifiedOrder($input);
                   $jsApiParameters = WxPayTools::GetJsApiParameters($wxOrder);
                   return $this->renderJson(['jsApiParameters' => $jsApiParameters], 0);
               } else {
                   //价格为0

                   $re = T_WX_PAY_LOG::P_WXMALL_PAY_GOODS('SUCCESS', ''
                       , $openId, 0, $random_order, 'price is zero', date("YmdHis")
                       , $attach);
                   if ($re != '1') {
                       return $this->renderJson(null, 1, '订单支付失败。(实际支付现金为0)');
                   }

                   return $this->renderJson(null, 100);
               }
           } else {
               return $this->renderJson(null, 1, '订单支付失败。');
           }
       }catch(\Exception $e){
        return $this->renderJson(null, 1, $e->getMessage());
    }
    }

    /**
     * 查看订单物流
     * @return \yii\web\Response
     */
    public function actionOrderLogistics($order_id)
    {
        $order = WxGoodDao::getOrderById($order_id);
        $orderDeliveryList = WxGoodDao::getOrderDeliveryList($order_id);
        if (count($orderDeliveryList) > 0) {
            foreach ($orderDeliveryList as &$orderDelivery) {
                $orderDelivery['GoodsList'] = WxGoodDao::getOrderdeliveryGoodsList($orderDelivery['ID']);
            }
        }

        return $this->render('order-logistics', ['order' => $order, 'orderDeliveryList' => $orderDeliveryList]);
    }

}